from django import template
from utils import util
from entities.consts import *

register = template.Library()


@register.filter(name='div')
def div(value, denominator=1):
    """ 除以指定的数字，保留两位小数 """
    try:
        ret = round((int(value) / denominator), 2)
    except Exception as e:
        ret = 0.00
    return ret


@register.filter(name='readable_seconds')
def readable_seconds(value):
    """ 将秒转化为可读的字符串 """
    try:
        ret = util.get_seconds_desp(value)
    except Exception as e:
        ret = value
    return ret


@register.filter(name='format_seconds')
def format_seconds(value):
    """ 将秒转化为可读的字符串 """
    try:
        value = int(value)
        hour = int(value / 3600)
        minute = int((value - hour*3600) / 60)
        second = (value - hour*3600) % 60
        ret = f'{hour:02d}:{minute:02d}:{second:02d}'
    except Exception as e:
        ret = value
    return ret


@register.filter(name='call_status')
def call_status(value):
    """ 将通话状态转化为可读的字符串 """
    status = {
        CALL_STATUS_NONE: '未接听',
        CALL_STATUS_CALLING: '正在通话中......',
        CALL_STATUS_DECLINE: '被呼叫方拒绝接听',
        CALL_STATUS_CANCEL: '呼叫方取消',
        CALL_STATUS_END: '通话结束',
        CALL_STATUS_SHUTDOWN: '被系统关闭',
    }

    try:
        ret = status.get(value, str(value))
    except Exception as e:
        ret = str(value)
    return ret


@register.filter(name='consume_type')
def consume_type(value):
    """ 将消费类型转化为可读的字符串 """
    status = {
        DIAMOND_OUTPUT_BUY_VIDEO: '短视频',
        DIAMOND_OUTPUT_VIDEO_CHAT: '视频通话',
        DIAMOND_OUTPUT_SEND_GIFT: '礼物',
        DIAMOND_OUTPUT_SEND_MESSAGE: '私信',
        DIAMOND_OUTPUT_BUY_VIP_CARD: '购买vip',
        DIAMOND_OUTPUT_TESTING: '测试',
    }

    try:
        ret = status.get(value, str(value))
    except Exception as e:
        ret = value
    return ret


@register.filter(name='tbs')
def thousand_bit_split(value, split_symbol=','):
    """ 千位分隔符分隔数字 """
    try:
        bits = [str(x) for x in str(value)]
        bits.reverse()

        new_bits = []
        index = 0
        for bit in bits:
            if index > 0 and index % 3 == 0:
                new_bits.append(split_symbol)
            index += 1
            new_bits.append(bit)
        new_bits.reverse()
        ret = ''.join(new_bits)
    except Exception as e:
        ret = value
    return ret


@register.filter(name='cdn')
def cdn(value):
    """ 修改CDN url """
    try:
        ret = util.cdn_url(value)
    except Exception as e:
        ret = value
    return ret
